<template>
<section v-if="sufreshCarts&&sufreshCarts.cartHeadInfo">
	<error v-if="!sufreshCarts.onehourCarts.length&&!sufreshCarts.reservedCarts.length&&!sufreshCarts.noSales.length" title="购物车空空如也"></error>
	<template v-else>
		<div class="cartGoods" v-if="sufreshCarts.onehourCarts.length && newestItemType == 0">
			<div class="tit" data-top="0">
				<span class="m-cb">
					<input type="checkbox"
						:checked="onehourChecked" 
						@click="selAllCart({item: sufreshCarts.onehourCarts.filter(item => !item.noSales )})" 
						:disabled="sufreshCarts.onehourCarts.every(item => !!item.noSales )">
					<i></i>
				</span>
				<em></em><span>一小时急速达商品</span>
				<!--<button @click="settlement(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</button>-->
			</div>
			<goods-detail :list="sufreshCarts.onehourCarts"></goods-detail>

			<!--
			<div class="showLater">
				<label for="all">
					<em>合计:<strong>¥{{ sufreshCarts.cartHeadInfo.totalAmount }}</strong></em>
					<span>(不含运费)</span>
				</label>
				<a v-if="sufreshCarts.onehourCartsNumber" href="javascript:void(0)" @click="settlement(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</a>
				<a v-else class="no-sale" href="javascript:void(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</a>
			</div>
			-->
		</div>

		<div class="cartGoods" v-if="sufreshCarts.reservedCarts.length">
			<div class="tit" data-top="0">
				<span class="m-cb">
					<input type="checkbox"
						:checked="reservedChecked" 
						@click="selAllCart({item: sufreshCarts.reservedCarts.filter(item => !item.noSales )})" 
						:disabled="sufreshCarts.reservedCarts.every(item => !!item.noSales )">
					<i></i>
				</span>
				<em></em><span>生鲜果蔬预订商品</span>
				<!--<button @click="settlement(1)">去结算({{ parseInt(sufreshCarts.reservedCartsNumber)>99?'99+':sufreshCarts.reservedCartsNumber }})</button>-->
			</div>

			<goods-detail :list="sufreshCarts.reservedCarts"></goods-detail>

			<!--
			<div class="showLater">
				<label for="all">
					<em>合计:<strong>¥{{ sufreshCarts.cartHeadInfo.preTotalAmount }}</strong></em>
					<span>(不含运费)</span>
				</label>
				<a v-if="sufreshCarts.reservedCartsNumber > 0" href="javascript:void(0)" @click="settlement(1)">去结算({{ parseInt(sufreshCarts.reservedCartsNumber)>99?'99+':sufreshCarts.reservedCartsNumber }})</a>
				<a v-else class="no-sale" href="javascript:void(0)">去结算({{ parseInt(sufreshCarts.reservedCartsNumber)>99?'99+':sufreshCarts.reservedCartsNumber }})</a>
			</div>
			-->
		</div>

		<!-- 如果最新的不是一小时达商品，则把区块放到下面，内容和上面的完全一样 -->
		<div class="cartGoods" v-if="sufreshCarts.onehourCarts.length && newestItemType == 1">
			<div class="tit" data-top="0">
				<span class="m-cb">
					<input type="checkbox"
						:checked="onehourChecked" 
						@click="selAllCart({item: sufreshCarts.onehourCarts.filter(item => !item.noSales )})" 
						:disabled="sufreshCarts.onehourCarts.every(item => !!item.noSales )">
					<i></i>
				</span>
				<em></em><span>一小时急速达商品</span>
				<!--<button @click="settlement(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</button>-->
			</div>
			<goods-detail :list="sufreshCarts.onehourCarts"></goods-detail>

			<!--
			<div class="showLater">
				<label for="all">
					<em>合计:<strong>¥{{ sufreshCarts.cartHeadInfo.totalAmount }}</strong></em>
					<span>(不含运费)</span>
				</label>
				<a v-if="sufreshCarts.onehourCartsNumber" href="javascript:void(0)" @click="settlement(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</a>
				<a v-else class="no-sale" href="javascript:void(0)">去结算({{ parseInt(sufreshCarts.onehourCartsNumber)>99?'99+':sufreshCarts.onehourCartsNumber }})</a>
			</div>
			-->
		</div>

		<!-- 无效商品 -->
		<div class="cartGoods" v-if="sufreshCarts.noSales.length">
			<div class="tit" data-top="0">
				<a href="javascript:void(0);" class="delall" @click="clearNoSales">清空失效商品</a>
				<span>失效商品</span>
			</div>
			<goods-detail :list="sufreshCarts.noSales"></goods-detail>
		</div>
	</template>

	<div class="showLaterBg"></div>
	<div class="showLater" v-if="sufreshCarts.onehourCarts.length || sufreshCarts.reservedCarts.length || sufreshCarts.noSales.length" v-transfer-dom>
		<label for="all">
			<span class="m-cb">
				<input type="checkbox" :checked="onehourChecked && reservedChecked && (sufreshCarts.onehourCartsNumber || sufreshCarts.reservedCartsNumber)" 
					:disabled="!sufreshCarts.onehourCarts.length && !sufreshCarts.reservedCarts.length"
					@click="selectAll">
				<i></i>
			</span>
			全选
			<em>合计:<strong>&yen;{{ totalPrice | formatPrice }}</strong></em>
			<p>（不含运费）</p>
		</label>
		<a v-if="sufreshCarts.onehourCartsNumber || sufreshCarts.reservedCartsNumber" href="javascript:void(0)" @click="preSettle">去结算({{ sufreshCarts.onehourCartsNumber + sufreshCarts.reservedCartsNumber }})</a>
		<a v-else href="javascript:void(0)" class="disabled">去结算</a>
	</div>

	<!-- 分别结算弹框 -->
	<div v-transfer-dom>
	<transition name="settle-channel-show">
	<div class="settle-channel" v-if="separateSettlement&&!(invalidItems && invalidItems.length)">
		<div class="content">
			<h3>请分开结算以下商品</h3>
			<div class="item">
				<a href="javascript:void(0);" class="btn" @click="settlement(0)">去结算</a>
				<p>一小时达</p>
				<p>共{{ sufreshCarts.onehourCartsNumber }}件，合计：<em>&yen;{{ sufreshCarts.cartHeadInfo.totalAmount }}</em><span>（不含运费）</span></p>
			</div>
			<div class="item">
				<a href="javascript:void(0);" class="btn" @click="settlement(1)">去结算</a>
				<p>生鲜预订</p>
				<p>共{{ sufreshCarts.reservedCartsNumber }}件，合计：<em>&yen;{{ sufreshCarts.cartHeadInfo.preTotalAmount }}</em><span>（不含运费）</span></p>
			</div>
			<a href="javascript:void(0);" class="close" @click="separateSettlement = false"></a>
		</div>
	</div>
	</transition>
	</div>
	
	<cart-validation-failed v-if="invalidItems && invalidItems.length" :cmmdty-info-items="allCmmdtyInfos" :invalid-items="invalidItems"></cart-validation-failed>
</section>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { TransferDomDirective as TransferDom } from 'vux'
import fetch from '@/config/fetch';
import * as domains from '@/config/env'
import GoodsDetail from './suFreshGoodsDetail.vue'
import error from '@/components/error'
import cartValidationFailed from '../../common/cartValidationFailed'

export default {
	name: 'cart',
	directives: {
		TransferDom
	},
	components: {
		GoodsDetail,
		error,
		cartValidationFailed
	},
	data() {
		return {
			separateSettlement: false // 分开结算弹框是否显示
		}
	},
	computed: {
		...mapGetters([
			'sufreshCarts',
			'cartsNumber'
		]),
		// 判断一小时达是否全选
		onehourChecked(){
			if(this.sufreshCarts){
				if(this.sufreshCarts.onehourCarts.every(item => !!item.noSales )){
					return true
				}
				return !this.sufreshCarts.onehourCarts.some(item => !item.noSales&&item.tickStatus==0 )
			}
		},
		// 判断生鲜预订是否全选
		reservedChecked(){
			if(this.sufreshCarts){
				if(this.sufreshCarts.reservedCarts.every(item => !!item.noSales )){
					return true
				}
				return !this.sufreshCarts.reservedCarts.some(item => !item.noSales&&item.tickStatus==0 )
			}
			
		},

		invalidItems() {
			return this.$store.state.cart1.invalidItems
		},

		allCmmdtyInfos() {
			return this.sufreshCarts.onehourCarts.concat(this.sufreshCarts.reservedCarts);
		},

		// 最新加入购物车的商品类型，用于判断列表先后顺序
		newestItemType() {
			let cmmdty, max = 0;

			this.allCmmdtyInfos.forEach(item => {
				let time = item.addTime;
				time = time.replace(/-/g, '/');
				time = time.split('.')[0];

				let t = new Date(time).getTime();
				if (t > max) {
					max = t;
					cmmdty = item;
				}
			});

			return cmmdty.salesType;
		},

		// 一小时达和生鲜预订的总价
		totalPrice() {
			return parseFloat(this.sufreshCarts.cartHeadInfo.totalAmount) + parseFloat(this.sufreshCarts.cartHeadInfo.preTotalAmount);
		}
	},
	methods: {
		...mapActions ([
			'updateCart',
			'selAllCart',
			'settlement'
		]),

		clearNoSales() {
			let that = this;

			AlertBox({
				type: "doubleBtn",
				alertType: "fixed",
				msg: "失效商品清空后无法恢复，是否清空？",
				confirmText: '清空',
				cancelText: '取消',
				confirm: function(){
					that.$store.commit('showMask', true);

					fetch({
						url: domains.tps + '/app/cart1/gateway/clearCartCmmdty.do',
						params: {
							app: 'wap',
							appVersion: '3.2.2',
							mdmCityCode: that.$store.state.position.cityCode,
							storeLocation: that.$store.state.position.storeLocation,
							areaId: that.$store.state.position.areaId
						},
						jsonp: 'callBack',
						jsonpCallback: 'clearNoSales'
					}).then(res => {
						if (res && res.code == 1) {
							that.$store.dispatch('getSufreshProducts');
						}
						else {
							AlertBox({type: 'mini',msg: res.msg});
						}
						that.$store.commit('showMask', false);
					}).catch(() => {
						this.$store.commit('showMask', false);
						AlertBox({type: 'mini',msg: '网络错误，请重试'});
					});
				}
			});
		},

		selectAll() {
			this.selAllCart({
				item: this.sufreshCarts.onehourCarts.concat(this.sufreshCarts.reservedCarts).filter(item => !item.noSales )
			});
		},
		
		preSettle() {
			if (this.sufreshCarts.onehourCartsNumber && this.sufreshCarts.reservedCartsNumber) {
				this.separateSettlement = true;
			}
			else if (this.sufreshCarts.onehourCartsNumber) {
				this.settlement(0);
			}
			else if (this.sufreshCarts.reservedCartsNumber) {
				this.settlement(1);
			}
		}
	},
	mounted (){
		this.$store.dispatch('getSufreshProducts')
	},
	created () {
		this.$store.commit('showMask', true)
	},
	updated (){
		this.$store.commit('showMask', false)
	}
}
</script>
<style lang="scss" scoped>




	@function _($px) {
		$rem: $px/50;
		@return #{$rem}rem;
	}
	section{
		width: 100%;
		overflow: hidden;
	}
	.tit {
		height: 2.24rem;
		line-height: 1.76rem;
		color: #444;
		font-size: .56rem;
		background-color: #f8f8f8;
		padding: 0 .8rem;
		z-index: 8888;
		overflow: hidden;
		border-top: _(22) solid #f1f1f1;
		em {
			background-image: url("/static/images/logo-54.png");
    		display: inline-block;
			width: .72rem;
			height: .72rem;
			background-repeat: no-repeat;
			background-size: contain;
			vertical-align: middle;
			margin-right: .16rem;
		}
		button {
			//display: none;
			width: 3.26rem;
			height: 1.2rem;
			float: right;
			border: 1px solid #ff782d;
			color: #ff782d;
			font-size: .48rem;
			text-align: center;
			margin: .28rem 0;
			background: #fff;
			border-radius: 2px;
			outline: none;
		}

		.delall {
			float: right;
			color: #333;
			font-size: _(24);
			&:before {
				display: inline-block;
				content: '';
				width: _(28);
				height: _(28);
				background: url(/static/images/del.png);
				background-size: contain;
				margin-right: _(8);
				vertical-align: middle;
			}
		}
	}

	.m-cb {
		position: relative;
		display: inline-block;
		vertical-align: middle;
		input[type=checkbox] {
			position: absolute;
			left: 0;
			top: 0;
			opacity: 0;
			width: .88rem;
			height: .88rem;
			cursor: pointer;
		}
		i {
			float: left;
			width: .88rem;
			height: .88rem;
			background: url(../images/unchecked.png) no-repeat;
			background-size: contain;
			margin-right: 5px;
		}
		input[type=checkbox]:checked+i {
		    background-image: url(../images/checked.png)
		}
	}

	.showLaterBg{
		width: 100%;
		height: _(96);
	}
	.showLater{
		position: fixed;
		bottom: 2.1rem;
		width: 100%;
		background-color: #fff;
		height: _(96);
		line-height: _(96);
		border-top: 1px solid #e8e8e8;
		padding-left: 0.8rem;
		a{
			display: inline-block;
			width: _(224);
			float: right;
			background: #ff782d;
			height: 100%;
			text-align: center;
			line-height: _(96);
			color: #fff;
			font-size: .6rem;
			&.disabled {
				background-color: #CCC;
			}
		}
		em {
			position: absolute;
			right: 4.7rem;
			top: _(10);
			font-size: .48rem;
			height: .72rem;
			line-height: 1;
			text-align: right;
			
		}
		strong {
			font-size: .72rem;
			color: #FF782D;
			margin-left: .12rem;
			font-weight: normal;
		}
		p{
			text-align: right;
			position: absolute;
			right: 4.7rem;
			top: .4rem;
			display: inline;
			color: #999;
			height: .72rem;
			font-size: _(20)
		}
	}

	.settle-channel {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .5);
		overflow: hidden;
		z-index: 510;
		color: #444;
		font-size: _(28);
		.content {
			position: absolute;
			width: 100%;
			left: 0;
			bottom: 0;
			padding-bottom: _(20);
			background: #FFF;
			h3 {
				height: _(80);
				margin-bottom: _(20);
				background: #F8F8F8;
				text-align: center;
				line-height: _(80);
			}
			.item {
				padding: _(30) _(28);
				line-height: _(40);
				em {
					font-size: _(32);
					color: #ff782d
				}
				span {
					color: #999;
				}
				.btn {
					float: right;
					width: _(200);
					height: _(80);
					line-height: _(80);
					background: #ff782d;
					border-radius: _(40);
					color: #FFF;
					font-size: _(30);
					text-align: center;
				}
			}
			.close {
				position: absolute;
				top: 0;
				right: 0;
				width: _(80);
				height: _(80);
				background: url(/static/images/close.png) no-repeat center;
				background-size: _(24);
			}
		}
	}

	.settle-channel-show-enter {
		opacity: 0;
	}
	.settle-channel-show-enter .content {
		bottom: -50%;
	}
	.settle-channel-show-enter-active {
		transition: all .3s;
	}
	.settle-channel-show-enter-active .content {
		transition: all .3s;
	}
	.settle-channel-show-leave-active {
		transition: all .3s;
		opacity: 0;
	}
	.settle-channel-show-leave-active .content {
		transition: all .3s;
		bottom: -50%;
	}
</style>

<style lang="scss">
.goodsdetail .vux-1px-tb {
	&:before { display: none;}
	&:after { display: none;}
}
</style>